package cn.wdm.ymcc.listener;


import cn.wdm.ymcc.domain.CourseOrder;
import cn.wdm.ymcc.dto.PayDto;
import cn.wdm.ymcc.service.ICourseOrderService;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(
        txProducerGroup = "courseOrderToPayTransaction"//监听哪一种事务消息组,与发送消息事务消息组别名
)
public class CourseOrderRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService iCourseOrderService;

    /**
     * 执行本地事务
     * @param message 往mq存放的数据，拿去给消费者消费 paydto
     * @param arg 额外的参数 o就是courseOrder
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        if(arg==null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        CourseOrder courseOrder= (CourseOrder) arg;
        try {
            iCourseOrderService.savaOrderAndOrderItems(courseOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
    /**
     * 检查本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] messageByte = (byte[]) message.getPayload();
            String s = new String(messageByte, StandardCharsets.UTF_8);
            PayDto payDto = JSONObject.parseObject(s, PayDto.class);
            CourseOrder courseOrder = iCourseOrderService.selectOrderByOrderNo(payDto.getOrderNo());
            return courseOrder!=null?RocketMQLocalTransactionState.COMMIT:RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
